package com.huatai.user.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huatai.common.util.AuthUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: ht-system
 * @description: token过滤
 * @author: songxiude
 * @create: 2023-02-16 09:01
 **/
//@Configuration
//@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
		String token = request.getHeader("Authorization");
		if(StringUtils.isNotBlank(token)){
			//网关层已做验证该过滤器不再验证token有效性
			String tokenkey = token.replace("bearer ", "");
			Claims claims = AuthUtil.getClaims(tokenkey);
			String userName = (String)claims.get("user_name");
			//获取用户的身份信息，权限信息
			String string = JSON.toJSONString(claims.get("authorities"));
			JSONArray array = JSON.parseArray(string);
			String[] authorities = array.toArray(new String[array.size()]);
			//身份信息、权限信息填充到用户身份token对象中
			UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(userName,null,
				AuthorityUtils.createAuthorityList(authorities));
			//创建details
			authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
			//将authenticationToken填充到安全上下文
			SecurityContextHolder.getContext().setAuthentication(authenticationToken);
		}
		chain.doFilter(request,response);
	}
}
